package com.zt.yzmlogin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zt.yzmlogin.service.YzmService;
import com.zt.yzmlogin.entity.User;
import com.zt.yzmlogin.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class YzmServiceImpl implements YzmService {

    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
    // 使用已实名制报备的签名
    private static final String SIGN_NAME = "保定理工";  // 修改为已实名制报备的签名

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean send(String phone, String coders) {
        // 验证手机号格式
        if (phone == null || !PHONE_PATTERN.matcher(phone).matches()) {
            System.err.println("手机号格式不正确：" + phone);
            return false;
        }

        // 验证验证码格式
        if (coders == null || !coders.matches("\\d{6}")) {
            System.err.println("验证码格式不正确，需要6位数字：" + coders);
            return false;
        }

        DefaultProfile profile=DefaultProfile.getProfile("cn-hangzhou","LTAI5t5ZPcbZ3QeV7yP6Jajo","HU7gQ89HYZU84xZ2xu0JzQQ12Kamwg");
        IAcsClient client=new DefaultAcsClient(profile);
        CommonRequest request=new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        Map<String,Object> map=new HashMap();
        map.put("coders",coders);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "保定理工学习");  // 使用常量定义的签名
        request.putQueryParameter("TemplateCode", "SMS_482855031");
        request.putQueryParameter("TemplateParam", JSON.toJSONString(map));

        System.out.println("发送短信参数：");
        System.out.println("手机号：" + phone);
        System.out.println("验证码：" + coders);
        System.out.println("签名名称：" + SIGN_NAME);
        System.out.println("模板参数：" + JSON.toJSONString(map));

        try {
            CommonResponse commonResponse = client.getCommonResponse(request);
            String responseData = commonResponse.getData();
            System.out.println("完整响应内容：" + responseData);

            // 解析响应内容
            Map<String, String> responseMap = JSON.parseObject(responseData, Map.class);
            String code = responseMap.get("Code");
            String message = responseMap.get("Message");

            if ("OK".equals(code)) {
                System.out.println("短信发送成功");
                return true;
            } else {
                System.err.println("短信发送失败，错误码：" + code + "，错误信息：" + message);
                if ("DB00313".equals(code)) {
                    System.err.println("签名未完成实名制报备，请在阿里云控制台完成签名实名制报备");
                }
                return false;
            }
        } catch (Exception e) {
            System.err.println("短信发送异常：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    @Transactional
    public User findOrCreateUser(String phone) {
        // 先查找用户
        User user = userMapper.findByPhone(phone);
        
        // 如果用户不存在，创建新用户
        if (user == null) {
            user = new User();
            user.setUsername(phone);  // 默认使用手机号作为用户名
            user.setPhone(phone);
            user.setPassword("");     // 手机验证码登录，不需要密码
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            userMapper.insert(user);
        }
        
        return user;
    }
}
